package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private final StringRedisTemplate stringRedisTemplate;

    private final CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        /*//1.从redis中查询商品缓存
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);

        //2.判断redis中是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在，返回商铺信息
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }

        //-缓存穿透：判断是否命中的是空值
        if (shopJson != null) {  //相当于：shopJson==""
            //返回错误信息
            return Result.fail("店铺不存在！");
        }

        //4.不存在，根据id查询数据库
        Shop shop = getById(id);

        //4.1 数据库中不存在，返回404
        if (shop == null) {

            //-缓存穿透：缓存空对象
            stringRedisTemplate.opsForValue().set(shopKey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);

            //返回控制信息
            return Result.fail("店铺不存在！");
        }

        //4.2存在，先把数据写入redis中，再去返回
        stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL,
        TimeUnit.MINUTES);*/
        //将代码封装

        //-缓存穿透
        //Shop shop = queryWithPassThrough(id);
        //使用工具类
        /*Shop shop = cacheClient.queryWithPassThrough(
                RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById,
                RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);*/

        //-缓存击穿
        //1.互斥锁解决缓存击穿
        /*Shop shop = queryWithMutex(id);
        if (shop==null){
            return Result.fail("店铺不存在！");
        }*/

        //2.逻辑过期
        //Shop shop = queryWithLogicalExpire(id);
        //使用工具类
        Shop shop = cacheClient.queryWithLogicalExpire(
                RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById,
                20L, TimeUnit.SECONDS,
                RedisConstants.LOCK_SHOP_KEY, RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS
        );

        if (shop == null) {
            return Result.fail("店铺不存在！");
        }

        //返回店铺信息
        return Result.ok(shop);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期：热点key问题
     *
     * @param id
     * @return
     */
    /*public Shop queryWithLogicalExpire(Long id) {
        //1.从redis中查询商品缓存
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);

        //2.判断redis中是否存在
        if (StrUtil.isBlank(shopJson)) {
            //3.未命中，直接返回null（因为数据已经预热过了，如果你查不到，说明你不是热点key，返回null）
            return null;
        }

        //4.命中，说明是热点key，把Json->Java对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //4.1 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //4.2 未过期，返回店铺信息
            return shop;
        }
        //4.3 已过期，需要缓存重建

        //5.缓存重建
        //5.1 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);

        //5.2 判断是否获取到锁
        if (isLock) {
            //再次检测是否过期
            if (expireTime.isAfter(LocalDateTime.now())) {
                //未过期，返回店铺信息
                return shop;
            }
            //5.2.1 成功，开启新的线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //重建缓存
                    this.saveShopToRedis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }

        //5.2.2 失败，返回商铺信息（过期的）
        return shop;
    }*/

    /**
     * 互斥锁
     *
     * @param id
     * @return
     */
    /*public Shop queryWithMutex(Long id) {
        //1.从redis中查询商品缓存
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);

        //2.判断redis中是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在，返回商铺信息
            return JSONUtil.toBean(shopJson, Shop.class);
        }

        //-缓存穿透：判断是否命中的是空值
        if (shopJson != null) {  //相当于：shopJson==""
            //返回错误信息
            return null;
        }

        //4.实现缓存重建
        //4.1 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);

            //4.2 判断是否获取到锁
            if (!isLock) {
                //4.3 失败->休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            //二次检查
            Shop doubleCheck = cacheClient.queryWithPassThrough(
                    RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById,
                    RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            if (doubleCheck != null) {
                return doubleCheck;
            }

            //4.4 成功，根据id查询数据库
            shop = getById(id);
            //4.4.1 数据库中不存在，返回404
            if (shop == null) {
                //-缓存穿透：缓存空对象
                stringRedisTemplate.opsForValue().set(shopKey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                //返回控制信息
                return null;
            }
            //4.4.2 存在，先把数据写入redis中，再去返回
            stringRedisTemplate.opsForValue().set(
                    shopKey, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL,
                    TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //4.5 释放互斥锁
            unLock(lockKey);
        }

        //5.返回店铺信息
        return shop;
    }*/

    /**
     * 封装缓存穿透的代码
     *
     * @param id
     * @return
     */
    /*public Shop queryWithPassThrough(Long id) {
        //1.从redis中查询商品缓存
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);

        //2.判断redis中是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在，返回商铺信息
            return JSONUtil.toBean(shopJson, Shop.class);
        }

        //-缓存穿透：判断是否命中的是空值
        if (shopJson != null) {  //相当于：shopJson==""
            //返回错误信息
            return null;
        }

        //4.不存在，根据id查询数据库
        Shop shop = getById(id);

        //4.1 数据库中不存在，返回404
        if (shop == null) {

            //-缓存穿透：缓存空对象
            stringRedisTemplate.opsForValue().set(shopKey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);

            //返回控制信息
            return null;
        }

        //4.2存在，先把数据写入redis中，再去返回
        stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL,
        TimeUnit.MINUTES);

        //5.返回店铺信息
        return shop;
    }*/


    /**
     * 获取锁
     *
     * @param key
     * @return
     */
    /*private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue()
                                          .setIfAbsent(key, "1",
                                                       RedisConstants.LOCK_SHOP_TTL,
                                                       TimeUnit.SECONDS);

        return BooleanUtil.isTrue(flag);
    }

    *//**
     * 释放锁
     *
     * @param key
     *//*
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    */

    /**
     * 缓存预热
     *//*
    public void saveShopToRedis(Long id, Long expireSeconds) throws InterruptedException {
        //1.查询店铺数据
        Shop shop = getById(id);

        //模拟延迟
        Thread.sleep(200);

        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3.写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }*/
    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空!");
        }

        //1.更新数据库
        updateById(shop);

        //2.删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);

        //3.返回结果
        return Result.ok();
    }

}
